package com.xzx.list;

import java.util.Arrays;

/**
 * @author xinzhixuan
 * @version V1.0.0
 * @date 2021/3/14
 **/
public class ArrayList implements List{

    private int[] arr;
    private int size = 0;

    @Override
    public List makeEmpty() {
        arr = new int[10];
        return this;
    }

    @Override
    public Integer findKth(int k) {
        if (k < size && k >=0) {
            return arr[k];
        }
        throw new RuntimeException("不存在位序");
    }

    @Override
    public int find(Integer x) {
        for (int i = 0; i<= size; i++) {
            if (arr[i] == x) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void insert(Integer x, int index) {
        if (size == arr.length) {
            throw new RuntimeException("表满");
        }

        if (index < 0 || index > size) {
            throw new RuntimeException("位置不合法");
        }

        for (int i = size; i > index; i--) {
            arr[i] = arr[i-1];
        }
        arr[index] = x;
        size += 1;
    }

    @Override
    public void delete(int index) {
        if (size == 0) {
            throw new RuntimeException("表空");
        }

        if (index < 0 || index > size) {
            throw new RuntimeException("位置不合法");
        }

        for (int i = index; i < size-1; i++) {
            arr[i] = arr[i+1];
        }
        size -= 1;
        arr[size] = 0;
    }

    @Override
    public int length() {
        return size;
    }

    @Override
    public String toString() {
        return Arrays.toString(arr);
    }
}
